Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

Example:
function(100)
= 5050

Ive come as far as creating a finite for loop as so:

let sum = 0
for (let i = 1; i <= 100; i++) {
    sum = sum + i;

//thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Well, it looks like you've got the basic premise sussed out for 1 to 100 - you're cycling through to the value and summing up. To put it into a bit of a nicer format:

const n = 100;

console.log(GetSumTo(n))

function GetSumTo(x) {
    var sum = 0;
    for (var i = 1; i <= x; i++) {
        sum = sum + i;
    }
    return sum;
}

Another option would be do it recursively:

const n = 100;

console.log(RecursiveSum(n, 0));

function RecursiveSum(val, sum) {
    if (val > 1) {
        sum = val + RecursiveSum(val - 1, sum);
    }
    else {
        sum = val;
    }
    return sum;
}

However, these can be time consuming when dealing with large values. Using a fancy bit of maths (explained here better than I can explain it: https://math.stackexchange.com/questions/1100897/sum-of-consecutive-numbers), we can find that the sum of consecutive numbers can be calculated with an easier formula: (n(n + 1))/2

Meaning we can just write a function to do that and save execution time:

const n = 100;

console.log(QuickSum(n));

function QuickSum(n) {
    var sum = n + 1;
    sum = sum * n;
    sum = sum / 2; //You could shrink the calculation to sum = (n * (n + 1)) / 2 I just did it over a few lines for readability
    return sum;
};

None of these options result in an infinite loop.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda